package com.wy.common.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 生成JSON Web令牌的工具类
 */
public class JwtHelper {

  //token过期时间
  private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;
  //加密秘钥
  private static String tokenSignKey = "wy1988#";

  //根据用户id和用户名称生成token字符串
  public static String createToken(Integer userId, String username) {
    String token = Jwts.builder()
        .setSubject("AUTH-USER")
        .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
        //有效载荷
        .claim("userId", userId)
        .claim("username", username)
        //加密处理
        .signWith(SignatureAlgorithm.HS512, tokenSignKey)
        //token字符串进行压缩
        .compressWith(CompressionCodecs.GZIP)
        .compact();
    return token;
  }

  public static Integer getUserId(String token) {
    try {
      if (StringUtils.isEmpty(token)) return null;

      Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
      Claims claims = claimsJws.getBody();
      Integer userId = (Integer) claims.get("userId");
      return userId;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public static String getUsername(String token) {
    try {
      if (StringUtils.isEmpty(token)) return "";

      Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
      Claims claims = claimsJws.getBody();
      return (String) claims.get("username");
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public static void removeToken(String token) {
    //jwttoken无需删除，客户端扔掉即可。
  }

}
